package com.tokenplus.thai.base

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.tokenplus.thai.anetwork.NetworkException
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

open class BaseViewModel : ViewModel(), BaseViewModelAction {

    private val mLiveDataLoading = MutableLiveData<Boolean>()
    private val mLiveDataNetException = MutableLiveData<NetworkException>()

    open fun eventAction(
        showLoading: Boolean = true,
        doing: suspend () -> Unit,
        error: suspend (Throwable) -> Unit,
        completed: suspend () -> Unit,
    ) {
        if (showLoading) {
            mLiveDataLoading.value = true
        }
        viewModelScope.launch(Dispatchers.IO) {
            try {
                doing()
            } catch (e: Exception) {
                error(e)
            } finally {
                completed()
            }
        }
    }

    override fun showLoading() {
        mLiveDataLoading.value = true
    }

    override fun dismissLoading() {
        mLiveDataLoading.value = false
    }

    override fun handleNetworkException(networkException: NetworkException) {
        mLiveDataNetException.value = networkException
    }

    override fun getLoadingLiveData(): MutableLiveData<Boolean> {
        return mLiveDataLoading
    }

    override fun getNetworkExceptionLiveData(): MutableLiveData<NetworkException> {
        return mLiveDataNetException
    }
}